package com.photoeditor.demo.model.face.report.reportlogic;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Handler;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.android.gl.view.SurfaceView;
import com.android.gpuimage.AdjustGPUImageView;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DebugUtil;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.photoeditor.R;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.bean.TemplateBean;
import com.photoeditor.demo.model.event.AgeSuccessEvent;
import com.photoeditor.demo.model.event.GotoAdVideoPageEvent;
import com.photoeditor.demo.model.event.GotoSubscribePageEvent;
import com.photoeditor.demo.model.event.VipMaskIsShowEvent;
import com.photoeditor.demo.model.face.SimpleImageAdapter;
import com.photoeditor.demo.model.face.TopSmoothScroller;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.subscribe.strategy.OneFreeStrategyManager;
import com.photoeditor.demo.model.subscribe.strategy.RateNewStrategyBean;
import com.photoeditor.demo.ui.activity.face.FaceLogicActivity;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.ImageManageUtil;
import com.photoeditor.demo.util.NetworkUtils;
import com.photoeditor.demo.util.face.FaceBaseCallback;
import com.photoeditor.demo.util.face.FaceUtil;
import com.photoeditor.demo.util.gl.My3DRenderer;
import com.photoeditor.demo.util.gl.OldifyEffectFactory;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.util.APKAssertImageLoader;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.face.FaceConstant;
import com.photoeditor.demo.model.bean.face.AgeResultBean;
import com.photoeditor.demo.model.bean.face.CommonFaceBean;
import com.photoeditor.demo.model.bean.face.FaceAgingResultBean;
import com.photoeditor.demo.ui.widget.face.FaceRectView;
import com.photoeditor.demo.ui.widget.oldify.OldifyDecorationContainer;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.util.BlurUtil;
import com.photoeditor.demo.util.FastBlur;
import com.photoeditor.demo.util.TimeConstant;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.transformation.BlurTransformation;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;

import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_FACE_AGING;
import static com.photoeditor.demo.model.preference.SpUtils.EFFECT_NAME;
import static com.photoeditor.demo.model.subscribe.strategy.OneFreeStrategyManager.ADVANCE_OBTAIN_RESULT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_NETWORK;
import static com.photoeditor.demo.util.measureTextViewSizeUtils.measureTextViewSize;

/**
 * Created by @author winn on 2018/10/30.
 */

public class FaceAgingReportLogic extends BaseReportLogic implements View.OnClickListener, OldifyEffectFactory.OnBuildOldifyImgListener {

    public static boolean ISBACK_2_HOME = false;

    @Bind(R.id.effect_img)
    ImageView mEffectImageView;
    @Bind(R.id.switch_image)
    View mSwitchImage;
    @Bind(R.id.loading_animation_view)
    LottieAnimationView mLoadingView;
    @Bind(R.id.view_draw_face)
    FaceRectView mViewDrawFace;
    @Bind(R.id.btnlist)
    View mBtnListParent;
    @Bind(R.id.pic_container)
    RelativeLayout mBgLayout;
    @Bind(R.id.rv)
    RecyclerView mRv;
    @Bind(R.id.tv_result)
    TextView mTvResult;
    @Bind(R.id.tv_other)
    TextView mTvOther;

    private SimpleImageAdapter mAdapter;

    private FaceAgingResultBean mResultBean;
    private Context mContext;
    private OldifyEffectFactory mOldifyEffectFactory;
    private FaceAgingProcessor mProcessor;

    private String mOriginImagePath;
    private String m50ImagePath;
    private String m70ImagePath;
    private String m90ImagePath;
    private String mSelectImagePath;
    private long mPageDisplayStartTime;
    private Bitmap mImgOnScreen;
    private CommonFaceBean mFaceBean;
    private int margin;
    private Bitmap mBackgroundBitmap;
    private Bitmap mOrgBitmap;
    private Bitmap mBluredUserBitmap;
    private Bitmap mBluredScreenBitmap;
    private AdjustGPUImageView mGPUImage;
    private SurfaceView mModelView;
    private OldifyDecorationContainer mDecorationView;
    private My3DRenderer mRender;
    private Map<String, String> mBase64CachedMap;
    private final String TEMPLATE_NO_ID = "no_id";
    private String mCurrentTemplateId;
    private String mCompressPic;
    private String mResultBase64;
    private int mLocation = 0;

    private int mEffectViewWidth, mEffectViewHeight;
    private Long startTime;
    private Activity mActivity;
    private TopSmoothScroller mTopScroller;
    private int mTemplatePosition = 0;
    private int mCurrentAge = 50;

    public void setActivity(Activity activity) {
        mActivity = activity;
        mTopScroller = new TopSmoothScroller(mActivity);
    }

    private boolean mIsModel;

    public FaceAgingReportLogic(String imagePath) {
        super(REPORT_TYPE_FACE_AGING);
        mOriginImagePath = imagePath;
        mBase64CachedMap = new HashMap<>();
    }

    public void setResultBean(FaceAgingResultBean resultBean) {
        mResultBean = resultBean;
        requestTemplates();
    }

    @Override
    public View getReportView(ViewGroup parent) {
        mContext = parent.getContext();
        ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(mContext)
                .inflate(R.layout.report_time_machine, parent, false);
        initView(viewGroup);

        updateViewIfNecessary();

        mProcessor = getFaceAgingProcessor();
        check50ForSub();

        return viewGroup;
    }

    private void initView(View rootView) {
        mContentView = rootView;
        ButterKnife.bind(this, mContentView);

        margin = DeviceUtils.dip2px(26);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mEffectImageView.getLayoutParams();
        mEffectViewWidth = DeviceUtils.getScreenWidthPx() - margin;
        mEffectViewHeight = DeviceUtils.getScreenWidthPx() - margin;
        layoutParams.height = mEffectViewHeight;
        layoutParams.width = mEffectViewWidth;

        layoutParams = (RelativeLayout.LayoutParams) mViewDrawFace.getLayoutParams();
        layoutParams.height = DeviceUtils.getScreenWidthPx() - margin;
        layoutParams.width = DeviceUtils.getScreenWidthPx() - margin;
        if (DebugUtil.isDebuggable() && !isVersionBelowKitKat()) {
            mViewDrawFace.setVisibility(View.VISIBLE);
        }

        mAdapter = new SimpleImageAdapter(this);
        setDefaultDataForAdapter();
        mAdapter.setOnItemClickListener(new SimpleImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, SimpleImageAdapter.SimpleAdapterData data, int postion) {
                mTemplatePosition = postion;
                if (postion > 2) {
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.STATISTIC_EVENT_PIC_CLICK, StatisticsConstant.STATISTIC_KEY_FACE_FUN, StatisticsConstant.STATISTIC_VALUE_AGING);
                    boolean isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isTemplateUnlocked(data.templateId);
                    OneTimeVipHelper.getInstance().setTemplateId(data.templateId);
                    if (!AppVipManager.isVip() && !mIsModel && !isCurrentAgeUnlocked) {
                        if (mMaskLayout != null) {
                            mMaskLayout.setVisibility(View.VISIBLE);
                        }
                        if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                            ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
                        }
                        return;
                    }

                    if (mMaskLayout != null) {
                        mMaskLayout.setVisibility(View.GONE);
                    }
                    if (!isLoading()) {
                        compressAndRequest(data.templateId, data.age);
                    }
                } else {
                    if (isLoading()) {
                        return;
                    }
                    boolean isCurrentAgeUnlocked = true;
                    switch (data.age) {
                        case 50:
                            isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isAgeUnlocked(50);
                            break;
                        case 70:
                            isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isAgeUnlocked(70);
                            break;
                        case 90:
                            isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isAgeUnlocked(90);
                            break;
                    }
                    if (!AppVipManager.isVip() && !mIsModel && !isCurrentAgeUnlocked) {
                        if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                            switch (data.age) {
                                case 50:
                                    OneTimeVipHelper.getInstance().setAge(50);
                                    mCurrentAge = 50;
                                    ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
                                    return;
                                case 70:
                                    OneTimeVipHelper.getInstance().setAge(70);
                                    mCurrentAge = 70;
                                    ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
                                    return;
                                case 90:
                                    OneTimeVipHelper.getInstance().setAge(90);
                                    mCurrentAge = 90;
                                    ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
                                    return;
                                default:
                                    break;
                            }
                        }
                    }
                    switch (data.age) {
                        case 50:
                            mCurrentAge = 50;
                            onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_50);
                            OneTimeVipHelper.getInstance().setAge(50);
                            break;
                        case 70:
                            mCurrentAge = 70;
                            onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_70);
                            OneTimeVipHelper.getInstance().setAge(70);
                            break;
                        case 90:
                            mCurrentAge = 90;
                            onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_90);
                            OneTimeVipHelper.getInstance().setAge(90);
                            break;
                        case R.id.switch_image:
                            if (mOnEventListener != null && !isLoading()) {
                                mOnEventListener.switchImage();
                            }
                            break;
                        default:
                    }
                }
            }
        });

        mRv.setAdapter(mAdapter);
        mRv.setLayoutManager(new LinearLayoutManager(rootView.getContext(), LinearLayoutManager.HORIZONTAL, false));
        mRv.setItemViewCacheSize(1);

        setTextViewSelected(mTvResult, true);
        setTextViewSelected(mTvOther, false);
    }

    public int getCurrentAge() {
        return mCurrentAge;
    }

    public String getCurrentTemplateId() {
        return mCurrentTemplateId;
    }

    private void setDefaultDataForAdapter() {
        List<SimpleImageAdapter.SimpleAdapterData> list = new ArrayList<>();
        SimpleImageAdapter.SimpleAdapterData data = new SimpleImageAdapter.SimpleAdapterData();
        data.resouceId = R.drawable.ic_old_40;
        data.age = 50;
        data.isVip = 1;
        data.selected = 1;
        OneTimeVipHelper.getInstance().setAge(50);
        list.add(data);
        data = new SimpleImageAdapter.SimpleAdapterData();
        data.resouceId = R.drawable.ic_old_50;
        data.age = 70;
        data.isVip = 1;
        list.add(data);
        data = new SimpleImageAdapter.SimpleAdapterData();
        data.resouceId = R.drawable.ic_old_50;
        data.age = 90;
        data.isVip = 1;
        list.add(data);
        mAdapter.setDatas(list);
    }


    /**
     * 更新用户头像和文案、设置/重置非vip遮罩
     */
    private void updateViewIfNecessary() {
        updateUserView();
        checkVipView();
        checkModelRequest();
    }

    /**
     * 更新用户头像
     */
    private void updateUserView() {
        mIsModel = FaceConstant.isModel(mOriginImagePath);

        if (mIsModel) {
            mOrgBitmap = APKAssertImageLoader.with(mContext.getResources()).load(mOriginImagePath).get();
        } else {
            mOrgBitmap = BitmapFactory.decodeFile(mOriginImagePath);
            if (mOrgBitmap != null && FaceLogicActivity.degree != 0) {  //旋转
                Matrix m = new Matrix();
                m.setRotate(FaceLogicActivity.degree, (float) mOrgBitmap.getWidth() / 2, (float) mOrgBitmap.getHeight() / 2);
                try {
                    mOrgBitmap = Bitmap.createBitmap(mOrgBitmap, 0, 0, mOrgBitmap.getWidth(), mOrgBitmap.getHeight(), m, true);
                } catch (OutOfMemoryError ex) {
                    //
                }
            }
        }
        if (mEffectImageView != null) {
            mEffectImageView.setImageBitmap(mOrgBitmap);
        }
        mSelectImagePath = mOriginImagePath;
    }


    private void createBluredMaskBitmap() {
        if (mBgLayout != null) {
            View activityView = mBgLayout;
            activityView.setDrawingCacheEnabled(true);
            activityView.destroyDrawingCache();
            activityView.buildDrawingCache();
            Bitmap bmp = activityView.getDrawingCache();
            if (bmp != null) {
                Bitmap copy = bmp.copy(Bitmap.Config.ARGB_8888, true);
                BlurUtil.blur(ComponentContext.getContext(), copy, 5);
                BlurUtil.drawDarkCover(copy);
                mBluredScreenBitmap = copy;
            }
            activityView.destroyDrawingCache();
            activityView.setDrawingCacheEnabled(false);
        }
    }

    private void createBluredUserBitmap(Bitmap srcBitmap) {
        int scaleRatio = 5;
        if (srcBitmap == null || srcBitmap.isRecycled()) {
            return;
        }
        Bitmap blurBitmap = srcBitmap.createScaledBitmap(srcBitmap,
                srcBitmap.getWidth() / scaleRatio,
                srcBitmap.getHeight() / scaleRatio,
                false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blurBitmap = BlurTransformation.blur(ComponentContext.getContext(), blurBitmap, 5);
        } else {
            blurBitmap = FastBlur.doBlur(blurBitmap, 5, true);
        }
        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBluredUserBitmap = Bitmap.createBitmap(blurBitmap.getWidth(), blurBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(mBluredUserBitmap);
        canvas1.drawBitmap(blurBitmap, 0, 0, bitmapPaint);
    }

    /**
     * 非vip用户弹出遮罩
     */
    private void checkVipView() {
        if (AppVipManager.isVip() || mIsModel) {
            if (mMaskLayout != null) {
                mMaskLayout.setVisibility(View.INVISIBLE);
            }

            return;
        }
        if (mMaskLayout != null) {
            createBluredUserBitmap(mOrgBitmap);                 //生成用户模糊图片
            mEffectImageView.setImageBitmap(mBluredUserBitmap); //设置用户模糊图片
            mMaskLayout.setVisibility(View.VISIBLE);
            ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                @Override
                public void run() {
                    createBluredMaskBitmap();
                    if (mBluredScreenBitmap != null) {
//                        mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                        BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                    }
                }
            }, 100);
            return;
        }
        //初始化非vip布局
        ViewStub maskStub = (ViewStub) mContentView.findViewById(R.id.stub_subscribe_mask);
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_SHOW,
                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING,
                StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_RATE_TIME_FACE_AGING);
        mMaskLayout = maskStub.inflate();
        AppCompatTextView textView = mMaskLayout.findViewById(R.id.btn_vip_confirm);
        measureTextViewSize(mActivity, textView, 200);
        createBluredUserBitmap(mOrgBitmap);             //生成用户模糊图片
        mEffectImageView.setImageBitmap(mBluredUserBitmap);   //设置用户模糊图片
        ThreadPool.runUITask(new Runnable() {           //设置全屏非Vip遮罩
            @Override
            public void run() {
                createBluredMaskBitmap();
                if (mBluredScreenBitmap != null) {
//                    mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                    BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                }
            }
        }, 100);
        //策略平台控制，0——旧样式，1——AD弹框，2——评分引导一天免费弹框
//        RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//        boolean value = SPDataManager.getTodayHasShowedAllSubscribeMaskCount() == 2;
//        if (value) {
//            DLog.d("wLog", "第二次进入模糊页，隐藏watch ad按钮");
//        } else {
//            DLog.d("wLog", "非第二次进入模糊页，应该展示watch ad按钮");
//        }
//        if (value || SPDataManager.isFirstCloseSubsPage() || ((beanConfig == null || beanConfig.getRateType() != ADVANCE_OBTAIN_RESULT))) {
//            //模糊页不展示watch video按钮
//            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//            lps.bottomMargin = DeviceUtils.dip2px(24);
//            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//            DLog.d("wLog", "*2*条件满足，隐藏watch ad按钮");
//            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
//        }
        if ((SPDataManager.getTodayHasShowedNorStickersSubscribeMaskCount() < 3)) {
            DLog.d("wLog", "前2次显示模糊页，则页面上不显示激励视频按钮，" +
                    "并在进入模糊页后自动跳转到主订阅页，从主订阅页返回到模糊页，并显示激励视频解锁按钮");
            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
            lps.bottomMargin = DeviceUtils.dip2px(24);
            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
            DLog.d("wLog", "*2*条件满足，隐藏watch ad按钮");
            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);

        }

        mMaskLayout.findViewById(R.id.rl_continue_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_BUTT_CLICK,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING,
                        StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_RATE_TIME_FACE_AGING);
                //跳转到订阅页面
                EventBus.getDefault().post(new GotoSubscribePageEvent());
            }
        });
        mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到激励视频
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING,
                        StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_RATE_TIME_FACE_AGING);
                SpUtils.obtain().save(EFFECT_NAME, "aging");
                EventBus.getDefault().post(new GotoAdVideoPageEvent());
            }
        });

        if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE) {
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                    StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                    StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_FACE_AGING,
                    StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_RATE_TIME_FACE_AGING);
        }

        if (mMaskLayout.getVisibility() == View.VISIBLE) {
                ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new VipMaskIsShowEvent());
                    }
                }, 1000);
            }
}

    private void resetData() {
        mResultBean = null;
        m50ImagePath = null;
        m70ImagePath = null;
        m90ImagePath = null;
        mBluredScreenBitmap = null;
    }

    /**
     * model的假loading请求
     * 2s后展示结果
     */
    private void checkModelRequest() {
        if (!mIsModel) {
            return;
        }
        showLoadingView(true);
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                showLoadingView(false);
                setDefaultModelView();
                if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                    ((FaceLogicActivity) mActivity).fakeScanReqSucc();
                }
            }
        }, 2000);
    }

    private void setDefaultModelView() {
        if (mIsModel) {
//            //设置头像
//            String path = FaceConstant.getModleOld30(mOriginImagePath);
//            Bitmap bitmap = APKAssertImageLoader.with(mContext.getResources()).load(path).get();
//            mEffectImageView.setImageBitmap(bitmap);
            checkAgeBtn(50);
        }
    }

    @Override
    public void updateImage(String imagePath) {
        if (TextUtils.equals(mOriginImagePath, imagePath)) {
            return;
        }
        mOriginImagePath = imagePath;
        if (FaceConstant.isModel(mOriginImagePath)) {
            if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).fakeScanReq();
            }
        }
        resetData();
        updateViewIfNecessary();
    }

    //生成背景
    private void createBackgroundBitmap(Bitmap srcBitmap) {
        int scaleRatio = 5;
        if (srcBitmap == null || srcBitmap.isRecycled()) {
            return;
        }
        Bitmap blurBitmap = srcBitmap.createScaledBitmap(srcBitmap,
                srcBitmap.getWidth() / scaleRatio,
                srcBitmap.getHeight() / scaleRatio,
                false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blurBitmap = BlurTransformation.blur(ComponentContext.getContext(), blurBitmap, 25);
        } else {
            blurBitmap = FastBlur.doBlur(blurBitmap, 25, true);
        }

        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        //background
        mBackgroundBitmap = Bitmap.createBitmap(blurBitmap.getWidth(), blurBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(mBackgroundBitmap);
        bitmapPaint.setAlpha(30);
        canvas1.drawBitmap(blurBitmap, 0, 0, bitmapPaint);
    }

    public void bindView(SurfaceView surfaceView, My3DRenderer render, AdjustGPUImageView gpuImage, OldifyDecorationContainer decView) {
        mModelView = surfaceView;
        mGPUImage = gpuImage;
        mRender = render;
        mDecorationView = decView;
        mOldifyEffectFactory = new OldifyEffectFactory(mContext, mImgOnScreen, mFaceBean, false);
        mOldifyEffectFactory.bindView(surfaceView, render, gpuImage, decView);
        mOldifyEffectFactory.setOnBuildOdifyImgListener(this);
    }

    public void setBottomLayoutVisible(boolean visible) {
        mBtnListParent.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
    }

    public Bitmap getBitmapOnScreen() {
        //穿过来的图片已经进行了优化，故不必再压缩
        Bitmap tmp = BitmapFactory.decodeFile(mOriginImagePath);
        if (tmp == null) return null;//fail

        Bitmap transformedTmp;
        try {
            mImgOnScreen = Bitmap.createBitmap(mEffectViewWidth, mEffectViewHeight, Bitmap.Config.ARGB_4444);
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
            System.gc();
            return null;
        }
        RectF dstBounds = new RectF(mEffectImageView.getDrawable().getBounds());
        Matrix transformableMatrix = mEffectImageView.getImageMatrix();
        transformableMatrix.mapRect(dstBounds, dstBounds);
        try {
            transformedTmp = Bitmap.createBitmap(tmp, 0, 0, tmp.getWidth(), tmp.getHeight(),
                    transformableMatrix, true);
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
            System.gc();
            return null;
        }
        if (mImgOnScreen == null) return null;
        if (transformedTmp == null) return null;

        Canvas canvas = new Canvas(mImgOnScreen);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        canvas.drawBitmap(transformedTmp, null, dstBounds, paint);

        if (transformedTmp != null && !transformedTmp.isRecycled()) transformedTmp.recycle();
        if (tmp != null && !tmp.isRecycled()) tmp.recycle();

        return mImgOnScreen;
    }

    public void setDetectFaceResult(CommonFaceBean faceBean) {
        mFaceBean = faceBean;
        showLoadingView(false);
        //draw face point in debug mode
        if (DebugUtil.isDebuggable()) mViewDrawFace.parseCommonFaceBeanNoDraw(mFaceBean);
    }

    public void onShowPointClick() {
        if (mViewDrawFace.getVisibility() == View.GONE) {
            mViewDrawFace.setCanDraw(true);
            mViewDrawFace.setVisibility(View.VISIBLE);
        } else if (mViewDrawFace.getVisibility() == View.VISIBLE) {
            if (!mViewDrawFace.canDraw()) {
                mViewDrawFace.setCanDraw(true);
                return;
            }
            mViewDrawFace.setCanDraw(false);
            mViewDrawFace.setVisibility(View.GONE);
        }
    }

    @Override
    public int getReportTitleResId() {
        return R.string.report_title_faceaging;
    }

    @Override
    public String getFeatureType() {
        return StatisticsConstant.STATISTIC_EVENT_FEATURE_VALUE_FEATURE_FACE_AGING;
    }

    @Override
    public boolean needScrool() {
        return true;
    }

    public void recoverLastChoosen() {
        if (OneTimeVipHelper.getInstance().getLatestUnlockedAge() != -1) {
            int age = OneTimeVipHelper.getInstance().getLatestUnlockedAge();
//            if (age == 50) {
//                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_50, mAtAge50);
//            } else if (age == 70) {
//                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_70, mAtAge70);
//            } else if (age == 90) {
//                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_90, mAtAge90);
//            }
        }
    }

    //in ui thread
    @Override
    public void onBuildOldifyImg(Bitmap bitmap, int oldifyType) {
        if (isLoading()) showLoadingView(false);
        mModelView.setVisibility(View.INVISIBLE);
        mGPUImage.setVisibility(View.INVISIBLE);
        mDecorationView.setVisibility(View.INVISIBLE);
        mProcessor.handleSuccess(bitmap, oldifyType);
    }

    public void check50ForSub() {
        onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_50);
    }

    public void checkTemplateBtn(String templateId) {
        int age = mAdapter.findAgeByTemplateId(templateId);
        if (age == -1) {
            return;
        }
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (mMaskLayout != null) {
                    mMaskLayout.setVisibility(View.GONE);
                }
                if (mOrgBitmap != null) {
                    mEffectImageView.setImageBitmap(mOrgBitmap);
                }
            }
        }, 100);

        compressAndRequest(templateId, age);
    }

    public void checkAgeBtn(int age) {
        if (mMaskLayout != null) {
            mMaskLayout.setVisibility(View.GONE);
        }
        switch (age) {
            case 50:
                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_50);
                break;
            case 70:
                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_70);
                break;
            case 90:
                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_90);
                break;
            default:
                break;
        }
    }

    private void onClickAgeBtn(final int age) {

        OneTimeVipHelper.getInstance().setAge(age);

        if (mIsModel) {
            if (mMaskLayout != null) {
                mMaskLayout.setVisibility(View.GONE);
            }
            boolean isNeedAnimation = false;
            switch (age) {
                case AgeResultBean.OLDIFY_TYPE_50:
                    if (TextUtils.isEmpty(m50ImagePath)) {
                        isNeedAnimation = true;
                    }
                    mSelectImagePath = FaceConstant.getModleOld30(mOriginImagePath);
                    m50ImagePath = mSelectImagePath;
                    break;
                case AgeResultBean.OLDIFY_TYPE_70:
                    if (TextUtils.isEmpty(m70ImagePath)) {
                        isNeedAnimation = true;
                    }
                    mSelectImagePath = FaceConstant.getModleOld40(mOriginImagePath);
                    m70ImagePath = mSelectImagePath;
                    break;
                case AgeResultBean.OLDIFY_TYPE_90:
                    if (TextUtils.isEmpty(m90ImagePath)) {
                        isNeedAnimation = true;
                    }
                    mSelectImagePath = FaceConstant.getModleOld50(mOriginImagePath);
                    m90ImagePath = mSelectImagePath;
                    break;
            }

           if(isNeedAnimation) {
               showLoadingView(true);
               new Handler().postDelayed(new Runnable(){
                   @Override
                   public void run() {
                       APKAssertImageLoader.with(mContext.getResources()).load(mSelectImagePath).into(mEffectImageView);
                       showLoadingView(false);
                   }

               }, 2000);
           } else {
               APKAssertImageLoader.with(mContext.getResources()).load(mSelectImagePath).into(mEffectImageView);
           }
        } else if (AppVipManager.isVip() || OneTimeVipHelper.getInstance().isAgeUnlocked(age)) {
            if (mMaskLayout != null) {
                mMaskLayout.setVisibility(View.GONE);
                mEffectImageView.setImageBitmap(mOrgBitmap);
            }
            mProcessor.processBtnClick(age);
        } else {
            if (age == 0) {
                mProcessor.processBtnClick(0);
                if (mMaskLayout != null) {
                    mMaskLayout.setVisibility(View.GONE);
                    mEffectImageView.setImageBitmap(mOrgBitmap);
                }
            } else {
                //非vip用户弹出遮罩
                if (mMaskLayout != null) {
                    mEffectImageView.setImageBitmap(mBluredUserBitmap);
                    createMaskBgBitmap();
                    mMaskLayout.setVisibility(View.VISIBLE);
//                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
//                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING);
                    return;
                }
                ViewStub maskStub = (ViewStub) mContentView.findViewById(R.id.stub_subscribe_mask);
                mMaskLayout = maskStub.inflate();
                mBluredUserBitmap = BlurUtil.blur2(ComponentContext.getContext(), mOrgBitmap, 10, 10);
                mEffectImageView.setImageBitmap(mBluredUserBitmap);
                createMaskBgBitmap();
                //策略平台控制，0——旧样式，1——AD弹框，2——评分引导一天免费弹框
                RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
                boolean value = SPDataManager.getTodayHasShowedAllSubscribeMaskCount() == 2;
                if (value) {
                    DLog.d("wLog", "第二次进入模糊页，隐藏watch ad按钮");
                } else {
                    DLog.d("wLog", "第二次进入模糊页，应该展示watch ad按钮");
                }
                if (value || (SPDataManager.getTodayHasShowedAllSubscribeMaskCount() == 2) || SPDataManager.isFirstCloseSubsPage() || ((beanConfig == null || beanConfig.getRateType() != ADVANCE_OBTAIN_RESULT))) {
                    //模糊页不展示watch video按钮
                    RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
                    lps.bottomMargin = DeviceUtils.dip2px(24);
                    mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
                    mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
                } else {
                    DLog.d("wLog", "不隐藏watch ad按钮");
                }
                mMaskLayout.findViewById(R.id.rl_continue_vip).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转到订阅页面
                        EventBus.getDefault().post(new GotoSubscribePageEvent());
                    }
                });
                mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转到激励视频
                        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                                StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FACE_AGING,
                                StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_FACE_AGING);
                        SpUtils.obtain().save(EFFECT_NAME, "aging");
                        EventBus.getDefault().post(new GotoAdVideoPageEvent());
                    }
                });

                if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE){
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING,
                            StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_FACE_AGING);
                }
            }
        }
    }

    /**
     * 首次订阅页返回时调用
     */
    public void updateMaskLayout() {
        if (mMaskLayout != null) {
            if (!AppVipManager.isVip() && !OneTimeVipHelper.getInstance().isAgeUnlocked()) {
                //既不是vip，当前age页没有解锁
                mMaskLayout.setVisibility(View.VISIBLE);
                checkVipView();
                RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
                lps.bottomMargin = DeviceUtils.dip2px(0);
                mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
                mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
                if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE) {
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_FACE_AGING,
                            StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_RATE_TIME_FACE_AGING);
                }
//                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
//                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
//                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING);
            }


//            RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//            boolean value = SPDataManager.getTodayHasShowedAllSubscribeMaskCount() != 2;
//            if (value) {
//                DLog.d("wLog", "非第二次进入模糊页，应该展示watch ad按钮, extra: " + ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)));
//            } else {
//                DLog.d("wLog", "非第二次进入模糊页，不应该显示watch ad按钮, extra: " + ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)));
//            }
//            if (value && (beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)) {
//                RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//                lps.bottomMargin = DeviceUtils.dip2px(0);
//                mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//                mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
////                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
////                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
////                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING);
//            } else {
//                DLog.d("wLog", "*1*条件不满足，不显示watch ad按钮");
//            }
        }
    }

    private void createMaskBgBitmap() {
        if (mBluredScreenBitmap == null) {
            View activityView = mBgLayout;
            activityView.setDrawingCacheEnabled(true);
            activityView.destroyDrawingCache();
            activityView.buildDrawingCache();
            Bitmap bmp = activityView.getDrawingCache();
            if (bmp != null) {
                Bitmap copy = bmp.copy(Bitmap.Config.ARGB_8888, true);
                BlurUtil.blur(mContext, copy, 10);
                BlurUtil.drawDarkCover(copy);
                mBluredScreenBitmap = copy;
                if (mMaskLayout != null) {
//                    mMaskLayout.setBackground(new BitmapDrawable(copy));
                    BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                }
            }
            activityView.destroyDrawingCache();
            activityView.setDrawingCacheEnabled(false);
        } else {
            if (mMaskLayout != null) {
//                mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
            }
        }
    }

    @Override
    public Bitmap getSaveImg() {
        if (getLocation() == 0) {

            if (mIsModel) {
                return APKAssertImageLoader.with(mContext.getResources()).load(mSelectImagePath).get();
            }
            return ImageHelper.getBitmapFromPath(mSelectImagePath);
        } else {
            if (!TextUtils.isEmpty(mResultBase64)) {
                return ImageManageUtil.base64ToBitmap(mResultBase64);
            } else {
                return mOrgBitmap;
            }
        }
    }


    public void showLoadingView(boolean show) {
        if (show) {
            if (!isLoading()) {
                mLoadingView.setVisibility(View.VISIBLE);
                mLoadingView.playAnimation();
            }
        } else {
            if (isLoading()) {
                mLoadingView.cancelAnimation();
                mLoadingView.setVisibility(View.GONE);
            }
        }
    }

    @OnClick({R.id.tv_result, R.id.tv_other, R.id.switch_image})
    public void onChangeTabClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_result:
                setTextViewSelected(mTvResult, true);
                setTextViewSelected(mTvOther, false);
                mLocation = 0;
                mTopScroller.setTargetPosition(0);
                mRv.getLayoutManager().startSmoothScroll(mTopScroller);
                break;
            case R.id.tv_other:
                setTextViewSelected(mTvOther, true);
                setTextViewSelected(mTvResult, false);
                mLocation = 1;
                mTopScroller.setTargetPosition(3);
                mRv.getLayoutManager().startSmoothScroll(mTopScroller);
                break;
            case R.id.switch_image:
                if (mOnEventListener != null && !isLoading()) {
                    mOnEventListener.switchImage();
                }
                break;
            default:
                break;
        }
    }

    public int getLocation() {
        if (mTemplatePosition < 3) {
            return 0;
        } else {
            return 1;
        }
    }

    private void setTextViewSelected(TextView textView, boolean selected) {
        if (selected) {
            textView.setTextColor(Color.parseColor("#9478FF"));
        } else {
            textView.setTextColor(Color.parseColor("#5E5D5D"));
        }
    }

    /**
     * 累计点击年龄按钮
     */
//    @OnClick({R.id.at_age_50, R.id.at_age_70, R.id.at_age_90, R.id.switch_image})
    public void onViewClicked(View view) {
        if (isLoading()) {
            return;
        }
        boolean isCurrentAgeUnlocked = true;
        switch (view.getId()) {
//            case R.id.at_age_50:
//                isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isAgeUnlocked(50);
//                break;
//            case R.id.at_age_70:
//                isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isAgeUnlocked(70);
//                break;
//            case R.id.at_age_90:
//                isCurrentAgeUnlocked = OneTimeVipHelper.getInstance().isAgeUnlocked(90);
//                break;
        }
        if (!AppVipManager.isVip() && !mIsModel && !isCurrentAgeUnlocked) {
            if (mActivity != null && mActivity instanceof  FaceLogicActivity) {
                switch (view.getId()) {
//                    case R.id.at_age_50:
//                        mSelBtn = mAtAge50;
//                        mSelBtn.setSelected(true);
//                        OneTimeVipHelper.getInstance().setAge(50);
//                        ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
//                        return;
//                    case  R.id.at_age_70:
//                        mSelBtn = mAtAge70;
//                        mSelBtn.setSelected(true);
//                        OneTimeVipHelper.getInstance().setAge(70);
//                        ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
//                        return;
//                    case  R.id.at_age_90:
//                        mSelBtn = mAtAge90;
//                        mSelBtn.setSelected(true);
//                        OneTimeVipHelper.getInstance().setAge(90);
//                        ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
//                        return;
                    default:
                        break;
                }
            }
        }
        switch (view.getId()) {
            case 50:
//                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_50, mAtAge50);
                OneTimeVipHelper.getInstance().setAge(50);
                break;
            case 70:
//                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_70, mAtAge70);
                OneTimeVipHelper.getInstance().setAge(70);
                break;
            case 90:
//                onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_90, mAtAge90);
                OneTimeVipHelper.getInstance().setAge(90);
                break;
            case R.id.switch_image:
                if (mOnEventListener != null && !isLoading()) {
                    mOnEventListener.switchImage();
                }
                break;
            default:
        }
    }

    public void destroy() {
        mProcessor.destroy();
    }

    public boolean isLoading() {
        return mLoadingView.getVisibility() == View.VISIBLE;
    }

    public void onBackPressed() {
        mProcessor.onBackPressed();
        mProcessor.handleResultFail(ComponentContext.getContext().getString(R.string.cancel_successful), STATISTIC_EVENT_FUN_VALUE_NETWORK);
    }

    public static boolean isVersionBelowKitKat() {
        return true;
    }

    private FaceAgingProcessor getFaceAgingProcessor() {
        return new OfflineProcessor();
    }

    class BaseFaceAgingProcessor implements FaceAgingProcessor {
        @Override
        public void processBtnClick(int age) {
        }

        @Override
        public void onBackPressed() {
        }

        @Override
        public boolean canUseCache(int age) {
            return false;
        }

        @Override
        public void handleSuccess(Bitmap bitmap, int oldifyType) {
        }

        @Override
        public void handleSuccess(AgeResultBean ageResultBean, int age) {
        }

        @Override
        public void destroy() {
        }

        @Override
        public void saveAndCache(AgeResultBean resultBean) {
        }

        @Override
        public void saveAndCache(Bitmap effect, int oldifyType) {
        }

        @Override
        public void handleResultFail(String message, String statisticsMessage) {
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_REQUEST_FAILED, StatisticsConstant.KEY_TREND_FUN,
//                    StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING, StatisticsConstant.KEY_REQUEST_FAILED_REASON, statisticsMessage);

//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_FAIL,
//                    StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
//                    StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING,
//                    StatisticsConstant.KEY_RESULT_FAIL_REASON, statisticsMessage);

            if (isLoading()) {
                showLoadingView(false);
            }
//            if (mSelBtn != null && mLastSelectBtn != null) {
//                mSelBtn.setSelected(false);
//                mSelBtn = mLastSelectBtn;
//                mSelBtn.setSelected(true);
//            }
            if (!TextUtils.isEmpty(message) && message.contains("CONCURRENCY_LIMIT_EXCEEDED")) {
                //并发限制错误，替换显示文案
                ToastUtil.showToast(mContext.getString(R.string.connection_lost_try_again));
            } else {
                ToastUtil.showToast(message);
            }
        }

        @Override
        public void loadCache(int type) {
            mSelectImagePath = getEffectSavePath(type);
            Bitmap bitmap = ImageHelper.getBitmapFromPath(mSelectImagePath);
            mEffectImageView.setImageBitmap(bitmap);
        }

        protected void setPageShowStartTime(long startTime) {
            mPageDisplayStartTime = startTime;
        }

        protected String getEffectSavePath(int type) {
            switch (type) {
                case AgeResultBean.OLDIFY_TYPE_NONE:
                    return mOriginImagePath;
                case AgeResultBean.OLDIFY_TYPE_50:
                    return FaceConstant.PATH_PHOTO + File.separator + "effect_50.jpg";
                case AgeResultBean.OLDIFY_TYPE_70:
                    return FaceConstant.PATH_PHOTO + File.separator + "effect_70.jpg";
                case AgeResultBean.OLDIFY_TYPE_90:
                    return FaceConstant.PATH_PHOTO + File.separator + "effect_90.jpg";
                default:
                    return null;
            }
        }

        protected String getStatisticsSuccessType() {
            if (mPageDisplayStartTime == 0) {
                mPageDisplayStartTime = System.currentTimeMillis();
            }
            long durationSec = (System.currentTimeMillis() - mPageDisplayStartTime) / TimeConstant.ONE_SEC;
            if (durationSec <= 4 && durationSec >= 0) {
                return StatisticsConstant.REQUEST_PAGE_VALUE_TIME_BELOW_4;
            } else if (durationSec <= 6) {
                return StatisticsConstant.REQUEST_PAGE_VALUE_TIME_BETWEEN_4_AND_6;
            } else if (durationSec <= 10) {
                return StatisticsConstant.REQUEST_PAGE_VALUE_TIME_BETWEEN_6_AND_10;
            } else {
                return StatisticsConstant.REQUEST_PAGE_VALUE_TIME_ABOVE_10;
            }
        }

    }

    private long startRequest;

    class OfflineProcessor extends BaseFaceAgingProcessor {

        private void checkRenderState() {
            if (mModelView.getVisibility() != View.VISIBLE)  mModelView.setVisibility(View.VISIBLE);
            if (mGPUImage.getVisibility() != View.VISIBLE) mGPUImage.setVisibility(View.VISIBLE);
            if (mDecorationView.getVisibility() != View.VISIBLE) mDecorationView.setVisibility(View.VISIBLE);
            if (!mOldifyEffectFactory.isRendering()) mOldifyEffectFactory.startRender();
        }

        @Override
        public void processBtnClick(int age) {
            super.processBtnClick(age);
            if (this.canUseCache(age)) return;

            if (mModelView == null || mGPUImage == null) {
//                ToastUtil.showToast(R.string.wait_age_camera);
                return;
            }
            checkRenderState();

            setPageShowStartTime(System.currentTimeMillis());

            showLoadingView(true);

//            StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING + "_" +
//                    StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC + "_"
//                    + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST);
            startRequest = System.currentTimeMillis();
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ,
//                    StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
//                    StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING);
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RESULT_REQ,
//                    StatisticsConstant.KEY_ALL_FUN, StatisticsConstant.ALL_FUN_VALUE_AGING);
            if (!mOldifyEffectFactory.oldify(age)) {
                handleResultFail(mContext.getString(R.string.net_connect_error),STATISTIC_EVENT_FUN_VALUE_NETWORK);
            }
        }

        @Override
        public void onBackPressed() {
            super.onBackPressed();
        }

        @Override
        public boolean canUseCache(int age) {
            boolean canUseCache = false;
            switch (age) {
                case OldifyEffectFactory.OLDIFY_TYPE_NONE:
                    canUseCache = true;
                    break;
                case OldifyEffectFactory.OLDIFY_TYPE_50:
                    canUseCache = TextUtils.isEmpty(m50ImagePath) ? false : true;
                    break;
                case OldifyEffectFactory.OLDIFY_TYPE_70:
                    canUseCache = TextUtils.isEmpty(m70ImagePath) ? false : true;
                    break;
                case OldifyEffectFactory.OLDIFY_TYPE_90:
                    canUseCache = TextUtils.isEmpty(m90ImagePath) ? false : true;
                    break;
            }
            if (canUseCache) loadCache(age);
            return canUseCache;
        }

        @Override
        public void handleSuccess(Bitmap bitmap, int oldifyType) {
            super.handleSuccess(bitmap, oldifyType);
            mEffectImageView.setImageBitmap(bitmap);
            sendAgeSuccessEvent();
            saveAndCache(bitmap, oldifyType);
//            StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING + "_" +
//                    StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC_SUCCESS + "_"
//                    + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST + "_" + getStatisticsSuccessType() );
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_RESULT_REQ_SUC,
//                    StatisticsConstant.KEY_ALL_FUN, StatisticsConstant.ALL_FUN_VALUE_AGING,
//                    StatisticsConstant.KEY_REQU_TIME, getStatisticsSuccessType());
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_SUCCESS,
//                    StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
//                    StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING,
//                    StatisticsConstant.KEY_REQUEST_TIME, getTimeInterval(startRequest));
        }

        @Override
        public void saveAndCache(final Bitmap effect, int oldifyType){
            final String path = getEffectSavePath(oldifyType);
            switch (oldifyType) {
                case OldifyEffectFactory.OLDIFY_TYPE_50:
                    m50ImagePath = new String(path);
                    break;
                case OldifyEffectFactory.OLDIFY_TYPE_70:
                    m70ImagePath = new String(path);
                    break;
                case OldifyEffectFactory.OLDIFY_TYPE_90:
                    m90ImagePath = new String(path);
                    break;
            }
            ThreadPool.runOnNonUIThread(new Runnable() {
                @Override
                public void run() {
                    ImageHelper.saveBitmapToSdcard(path, effect);
                }
            });
            mSelectImagePath = new String(path);
        }

        @Override
        public void destroy() {
            super.destroy();
            if (mOldifyEffectFactory != null) {
                mOldifyEffectFactory.destroy();
            }
        }
    }

    /**
     * 获取接口请求的耗时区间
     *
     * @param startRequest 开始请求时间
     * @return 区间文本
     */
    private String getTimeInterval(long startRequest) {
        long successRequest = System.currentTimeMillis();
        long diff = successRequest - startRequest;
        float second = diff / 1000f;
        String secondText = "";
        if (second < 4) {
            secondText = "[0.4)";
        } else if (second >= 4 && second < 6) {
            secondText = "[4.6)";
        } else if (second >= 6 && second < 10) {
            secondText = "[6.10)";
        } else if (second >= 10) {
            secondText = "[10.)";
        }
        return secondText;
    }

    public void choose50Age() {
//        onClickAgeBtn(AgeResultBean.OLDIFY_TYPE_50, mAtAge50);
    }

    /**
     * 发送老化完成的事件用于更新结果页的模糊图片
     */
    private void sendAgeSuccessEvent() {
        if (!AppVipManager.isFaceAgingVip()) {
            EventBus.getDefault().post(new AgeSuccessEvent());
        }
    }

    @Override
    public void onSubscribeSuccess() {
//        mAtAge50.updateVip(true);
//        mAtAge70.updateVip(true);
//        mAtAge90.updateVip(true);
        if (mAdapter != null) {
            ThreadPool.runUITask(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
        checkAgeBtn(OneTimeVipHelper.getInstance().getAge());
    }

    interface FaceAgingProcessor {
        void processBtnClick(int age);

        void onBackPressed();

        void destroy();

        void handleSuccess(Bitmap bitmap, int oldifyType);

        void handleSuccess(AgeResultBean ageResultBean, int age);

        boolean canUseCache(int age);

        void loadCache(int type);

        void saveAndCache(AgeResultBean resultBean);

        void saveAndCache(Bitmap effect, int oldifyType);

        void handleResultFail(String message, String statisticsMessage);
    }


    private void requestTemplates() {
        FaceUtil.requestAgingTemplates(mResultBean.sex, mResultBean.ethnicity.toLowerCase(),this, new FaceBaseCallback() {
            @Override
            public void onSuccess(Response response) {
                ThreadPool.runUITask(new Runnable() {
                    @Override
                    public void run() {
                        if (mActivity != null) {
                            ((FaceLogicActivity)mActivity).stopLoadingAnimation();
                        }
                    }
                });
                okhttp3.Response rawResponse = response.getRawResponse();
                if (rawResponse == null) {
//                    hideLoading();
//                    tryGetTemplatesAgain();
                    return;
                }
                ResponseBody responseBody = rawResponse.body();
                if (responseBody == null) {
//                    hideLoading();
//                    tryGetTemplatesAgain();
                    return;
                }
//                mOtherAdapter.setDatas();
                new ParseTemplateBodyTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, responseBody);
            }

            @Override
            public void onError(Response response) {
                ThreadPool.runUITask(new Runnable() {
                    @Override
                    public void run() {
                        if (mActivity != null) {
                            ((FaceLogicActivity)mActivity).stopLoadingAnimation();
                        }
                    }
                });
                super.onError(response);
            }
        });
    }

    class ParseTemplateBodyTask extends AsyncTask<ResponseBody, Void, List<TemplateBean>> {
        @Override
        protected List<TemplateBean> doInBackground(ResponseBody... responseBodies) {
            if (responseBodies == null || responseBodies.length < 1) {
                return null;
            }
            ResponseBody responseBody = responseBodies[0];
            try {
                String result = responseBody.string();
                if (TextUtils.isEmpty(result)) {
//                    hideLoading();
                    return null;
                }
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.optInt("code");
                if (code == 3) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
//                            hideLoading();
                            ToastUtil.showToast(R.string.concurrency_limit_tip);
                        }
                    });
                    return null;
                }
                if (!jsonObject.optBoolean("success")) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
//                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                String dataString = jsonObject.optString("data");
                if (TextUtils.isEmpty(dataString)) {
                    return null;
                }

                Type type = new TypeToken<List<TemplateBean>>(){}.getType();
                Gson gson = new Gson();
                List<TemplateBean> list = gson.fromJson(dataString, type);
                if (list == null || list.isEmpty()) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
//                            hideLoading();
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                return list;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
//            tryGetTemplatesAgain();
            return null;
        }

        @Override
        protected void onPostExecute(List<TemplateBean> templateBeans) {
            if (templateBeans == null || templateBeans.isEmpty()) {
                return;
            }
            List<SimpleImageAdapter.SimpleAdapterData> list = new ArrayList<>();
            int size = templateBeans.size();
            for(int i=0; i<size; i++) {
                TemplateBean bean = templateBeans.get(i);
                SimpleImageAdapter.SimpleAdapterData data = new SimpleImageAdapter.SimpleAdapterData();
                data.imagePath = bean.getThumbnailUrl();
                if (i == 0) {
                    data.isVip = 0;
                    OneTimeVipHelper.getInstance().forceUnlockTemplate(bean.getTemplateId());
                } else {
                    data.isVip = 1;
                }
                data.templateId = bean.getTemplateId();
                if (!TextUtils.isEmpty(bean.getAge())) {
                    data.age = Integer.valueOf(bean.getAge());
                }
                list.add(data);
            }
            mAdapter.addDatas(list);
            mAdapter.notifyDataSetChanged();
        }
    }

    private String TAG = FaceAgingReportLogic.class.getSimpleName();
    /**
     * 压缩图片，请求接口
     */
    private void compressAndRequest(String templateId, int age) {
        mCurrentTemplateId = templateId;
        String cachedBitmapBase64 = mBase64CachedMap.get(templateId);
        if (!TextUtils.isEmpty(cachedBitmapBase64)) {
            showSwapPic(cachedBitmapBase64);
            return;
        }

//        if (!TextUtils.isEmpty(mResultBase64)) {
//            showSwapPic(mResultBase64);
//            return;
//        }
//        showLoading();
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                if (mResultBean == null) {
                    if (mOnEventListener != null) {
                        mOnEventListener.updateResultBean();
                    }
                    return;
                }
                //增加压缩缓存，因为原图和模板合并，原图pic是固定，只需要压缩一次，就可以，下次请求可以复用
                if (!TextUtils.isEmpty(mCompressPic)) {
                    requestFaceAging(mCompressPic, templateId, age);
                    return;
                }
                //
                Bitmap bitmap = ImageHelper.getBitmapFromPath(mOriginImagePath);
                if (bitmap == null){
//                    Toast.makeText(mActivity, "bitmap is empty", Toast.LENGTH_SHORT).show();
                    return;
                }
                //压缩图片
                Bitmap bitmap1 = ImageHelper.compressJpgToLimitKB(bitmap, 100);
                if (bitmap1 == null){
//                    Toast.makeText(mActivity, "bitmap is empty", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    mCompressPic = ImageHelper.bitmapToBase64(bitmap1);
                    DLog.i(TAG, "onSuccess: compressImage");
                    requestFaceAging(mCompressPic, templateId, age);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showSwapPic(final String pic) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                ImageLoader.loadImageFromBase64(ComponentContext.getContext(), pic, mEffectImageView);
            }
        });
    }

    private void requestFaceAging(String pic, String templateId, int age) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                showLoadingView(true);
            }
        });
        startRequest = System.currentTimeMillis();
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING);

        DLog.e(TAG, "requestFaceAging");
        FaceUtil.requestFaceAging(pic, templateId, String.valueOf(age), mResultBean.sex, mResultBean.ethnicity.toLowerCase(), this, new FaceBaseCallback() {
            @Override
            public void onSuccess(Response response) {
                DLog.e(TAG, "requestFaceAging -> success");
                //network error
                if (!NetworkUtils.isNetworkAvailable(mActivity)){
                    showLoadingView(false);
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_FAIL,
                            StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                            StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING,
                            StatisticsConstant.KEY_RESULT_FAIL_REASON, "network");
                    return;
                }
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_SUCCESS,
                        StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                        StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING,
                        StatisticsConstant.KEY_REQUEST_TIME, getTimeInterval(startRequest));

                okhttp3.Response rawResponse = response.getRawResponse();
                if (rawResponse == null) {
                    showLoadingView(false);
//                    tryGetTemplatesAgain();
                    return;
                }
                ResponseBody responseBody = rawResponse.body();
                if (responseBody == null) {
                    showLoadingView(false);
//                    tryGetTemplatesAgain();
                    return;
                }
                new ParseBodyTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, responseBody);
            }

            @Override
            public void onError(Response response) {
//                hideLoading();
                DLog.e(TAG, "requestFaceAging -> onError");
//                tryGetTemplatesAgain();
//                statisFaild();
                ToastUtil.showToast(R.string.gender_swap_failed);
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_MERGE_REQ_FAIL,
                        StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                        StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.MAIN_PAGE_VALUE_FACE_AGING,
                        StatisticsConstant.KEY_RESULT_FAIL_REASON, response.message());
            }
        });
    }

    class ParseBodyTask extends AsyncTask<ResponseBody, Void, String> {
        @Override
        protected String doInBackground(ResponseBody... responseBodies) {
            if (responseBodies == null || responseBodies.length < 1) {
                ThreadPool.runUITask(new Runnable() {
                    @Override
                    public void run() {
                        showLoadingView(false);
                    }
                });
                return null;
            }
            ResponseBody responseBody = responseBodies[0];
            try {
                String result = responseBody.string();
                if (TextUtils.isEmpty(result)) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingView(false);
                        }
                    });
                    return null;
                }
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.optInt("code");
                if (code == 3) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingView(false);
                            ToastUtil.showToast(R.string.concurrency_limit_tip);
                        }
                    });
                    return null;
                }
                if (!jsonObject.optBoolean("success")) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingView(false);
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                JSONObject dataJsonObj = jsonObject.optJSONObject("data");
                if (dataJsonObj == null) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingView(false);
                        }
                    });
                    return null;
                }
//                mUsedTemplateId = dataJsonObj.optString("templateId");
//                mOtherAdapter.removeDataByTemplateId(mUsedTemplateId);
                String picBase64 = dataJsonObj.optString("templateBase64Str");
                if (TextUtils.isEmpty(picBase64)) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingView(false);
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                //统计
//                requestSucceedStat(getTimeInterval(startRequest));
                DLog.i(TAG, "onSuccess: " + picBase64);
                return picBase64;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
//            tryGetTemplatesAgain();
            return null;
        }

        @Override
        protected void onPostExecute(String picBase64) {
            super.onPostExecute(picBase64);
            showLoadingView(false);
            mResultBase64 = picBase64;
            if (!TextUtils.isEmpty(mResultBase64)) {
                mBase64CachedMap.put(mCurrentTemplateId, picBase64);
                //显示到image view
                showSwapPic(mResultBase64);
            }
        }
    }

}
